#include <iostream>
#include <string>
#include <cstring>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <cerrno>

void* work(void* args)
{
   int sock=*(int*)args;
    delete (int*)args;
    pthread_detach(pthread_self());

    char buf[1024];
    memset(buf,0,1024);
    ssize_t s=recv(sock,buf,sizeof(buf),0);
    if(s>0)
    {
        buf[s]=0;
        std::cout<<buf;
    }
    std::string str="http/1.0 mujuan sb\n";
    str+="Content-type : text/plain\n";
    str+="\n";
    str+="Mujuan sbbbb";
    send(sock,str.c_str(),str.size(),0);
    close(sock);
    return nullptr;
}

const uint16_t port=8080;

int main()
{
   int lsock=socket(AF_INET,SOCK_STREAM,0);
    if(lsock<0)
    {
        std::cerr<<"socket creat error"<<errno<<std::endl;
        return 1;
    }

    struct sockaddr_in local;
    local.sin_family=AF_INET;
    local.sin_port=htons(port);
    local.sin_addr.s_addr=inet_addr("10.0.24.7");
    //local.sin_addr.s_addr=INADDR_ANY;

    if(bind(lsock,(struct sockaddr*)&local,sizeof(local))<0)
    {
          std::cerr<<"socket bind error"<<errno<<std::endl;
          return 2;
    }
    
    if(listen(lsock,5)<0)
    {
          std::cerr<<"socket bind error"<<errno<<std::endl;
          return 3;
    }
    while(1)
    {
        int sock= accept(lsock,nullptr,nullptr);
        if(sock>0)
        {
            pthread_t tid;
            int*parm=new int(sock);
            pthread_create(&tid,nullptr,work,(void*)parm);
        }
    }
}